package team.paimengshop.show;

import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import team.paimengshop.server_database.UserInfoOperate;
import team.paimengshop.server_dataclass.User;
import team.paimengshop.server_socket.ActionControl_Receive;
import team.paimengshop.server_socket.ActionControl_Send;
import team.paimengshop.server_socket.ReceiveFromClient;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Objects;
import java.util.ResourceBundle;

public class customerServiceforServerController implements Initializable
{
    public static int MyId = 0;

    @FXML
    private AnchorPane servicePane;

    @FXML
    private TextField inputField;

    @FXML
    private ScrollPane scrollPane;

    @FXML
    private VBox vBox;

    @FXML
    private Button imgBtn;

    @FXML
    private Button sendBTn;

    @FXML
    private Label label;


    public void ShowChatMessage(int userId, String message)
    {
        Platform.runLater(new Runnable()
        {
            @Override
            public void run()
            {
                HBox unit = getMessageUnitText(userId, message);
                unit.getStyleClass().add("font-chat");
                vBox.getChildren().add(unit);
                scrollPane.setVvalue(scrollPane.getVmax());
            }
        });
    }

    public void ShowChatImage(int userId, File file)
    {
        Platform.runLater(new Runnable()
        {
            @Override
            public void run()
            {
                HBox unit = getMessageUnitImg(userId, file.toString());
                unit.getStyleClass().add("font-chat");
                vBox.getChildren().add(unit);
                scrollPane.setVvalue(scrollPane.getVmax());
            }
        });
    }


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle)
    {
        servicePane.getStylesheets().add(getClass().getResource("All.css").toExternalForm());

        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);      //无需左右滚动
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        //滚动监听
        scrollPane.hvalueProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                scrollPane.setVvalue(1);
            }
        });

        vBox.setPadding(new Insets(30));
//        flowPane.setOrientation(Orientation.VERTICAL);


        label.setText("客户");
        label.setAlignment(Pos.CENTER);
        label.getStyleClass().add("label-service");
        label.getStyleClass().add("label-forpaiMeng");

        inputField.setPromptText("回复");
        inputField.getStyleClass().add("input-group");

        sendBTn.setText("发送");
        sendBTn.getStyleClass().add("btn-basic");

        scrollPane.getStyleClass().add("pane-radius-large");

        imgBtn.setPrefWidth(60);
        imgBtn.setPrefHeight(60);
        imgBtn.setGraphic(new ImageView(new Image("file:PaiMengShop/PaiMengShopServer/src/main/resources/team/paimengshop/show/image/img.png")));
        imgBtn.getStyleClass().add("button-transparent-special-forImgBtn");
    }

    @FXML
    void OnimgBtnCLicked(ActionEvent event)
    {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择图片");


        //我们可以通过设置initialDirectory和title属性来配置文件选择器对话框窗口

        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Images", "*.*"),
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("GIF", "*.gif"),
                new FileChooser.ExtensionFilter("BMP", "*.bmp"),
                new FileChooser.ExtensionFilter("PNG", "*.png")
        );

        File file = fileChooser.showOpenDialog(servicePane.getScene().getWindow());

        if(file!=null)          //当用户直接关闭选择文件窗口的时候会使file为null
        {
            JSONArray jsonArray = ActionControl_Send.Communication(file);
            ReceiveFromClient.getSend().Send(jsonArray);

            HBox unit = getMessageUnitImg(MyId,file.toString());

            vBox.getChildren().add(unit);
            scrollPane.setVvalue(scrollPane.getVmax());//当发送者点击发送时，自动到最底下（稍微有点瑕疵）
        }
    }

    @FXML
    void OnsendBtnClicked(ActionEvent event)
    {
        if(!Objects.equals(inputField.getText(), ""))    //若用户输入为空，则不发送
        {
            HBox unit = getMessageUnitText(MyId,inputField.getText());
            unit.getStyleClass().add("font-chat");
            vBox.getChildren().add(unit);
            scrollPane.setVvalue(scrollPane.getVmax());     //当发送者点击发送时，自动到最底下（稍微有点瑕疵）

            JSONArray jsonArray =  ActionControl_Send.Communication(inputField.getText());
            ReceiveFromClient.getSend().Send(jsonArray);

            inputField.clear();
        }

//        flowPane.getChildren().add(unit);
    }

    /*
     *@param id:若为0，则为客服id；不为0，则为用户id
     *
     */
    public static HBox getMessageUnitText(int id,String text)       //获取聊天单元(文本)
    {
        if(id!=0)
        {
            HBox unit1 = new HBox();
            unit1.setPrefWidth(1119);
            unit1.setAlignment(Pos.BASELINE_LEFT);
            Label textLabel = new Label();
            textLabel.getStyleClass().add("label-chat");
            textLabel.setText(text);

            User user = UserInfoOperate.FindById(id);

            Image image1 = new Image(user.getHeadImageURL());
            ImageView imageView1 = new ImageView(image1);
            imageView1.setFitHeight(60);
            imageView1.setFitWidth(60);
            unit1.getChildren().add(imageView1); //应为用户的头像
            unit1.getChildren().add(textLabel);


            return unit1;
        }
        else
        {
            HBox unit2 = new HBox();
            unit2.setPrefWidth(1119);
            unit2.setAlignment(Pos.BASELINE_RIGHT);
            Label textLabel = new Label();
            textLabel.getStyleClass().add("label-chat");

            textLabel.setText(text);

            Image image2 = new Image("file:PaiMengShop/PaiMengShopServer/src/main/resources/team/paimengshop/show/image/business.png");
            ImageView imageView2 = new ImageView(image2);
            imageView2.setFitHeight(60);
            imageView2.setFitWidth(60);

            unit2.getChildren().add(textLabel);
            unit2.getChildren().add(imageView2);   //应为商户的头像
            return unit2;
        }
    }

    public static HBox getMessageUnitImg(int id,String imgPath)       //获取聊天单元(图片)
    {
        if(id!=0)
        {
            HBox unit1 = new HBox();
            Image img = new Image("file:" + imgPath);
            ImageView view = new ImageView(img);
            view.setFitHeight(200);
            view.setFitWidth(200);


            User user = UserInfoOperate.FindById(id);

            Image image1 = new Image(user.getHeadImageURL());
            ImageView imageView1 = new ImageView(image1);
            imageView1.setFitHeight(60);
            imageView1.setFitWidth(60);


            unit1.getChildren().add(imageView1); //应为用户的头像
            unit1.getChildren().add(view);

            unit1.setAlignment(Pos.BASELINE_LEFT);
            return unit1;
        }
        else
        {
            HBox unit2 = new HBox();
            Image img = new Image("file:" + imgPath);
            ImageView view = new ImageView(img);
            view.setFitHeight(200);
            view.setFitWidth(200);

            Image image2 = new Image("file:PaiMengShop/PaiMengShopServer/src/main/resources/team/paimengshop/show/image/business.png");
            ImageView imageView2 = new ImageView(image2);
            imageView2.setFitHeight(60);
            imageView2.setFitWidth(60);


            unit2.getChildren().add(view);
            unit2.getChildren().add(imageView2); //应为商户的头像

            unit2.setAlignment(Pos.BASELINE_RIGHT);
            return unit2;
        }
    }
}
